import { shareIdCallBack } from '/utils/bridge/shareId/index.js'
import { getAccountInfo } from '/utils/bridge/accountinfo/index.js'

export function statusBarHeight() {
  const ua = window.navigator.userAgent.toLocaleLowerCase()
  const patternHeight = /headerviewheight=(\d+)/
  let statusHeight = '20px'
  if (patternHeight.test(ua)) {
    statusHeight = patternHeight.exec(ua)[1] + 'px'
  }
  // console.log('statusHeight', statusHeight)
  return statusHeight
}
export function statusBarHeightValue() {
  const ua = window.navigator.userAgent.toLocaleLowerCase()
  const patternHeight = /headerviewheight=(\d+)/
  let statusHeight = 20
  if (patternHeight.test(ua)) {
    statusHeight = patternHeight.exec(ua)[1]
  }
  return statusHeight
}

export function headerHeight() {
  const statusHeight = statusBarHeight()
  return parseInt(statusHeight) + 44 + 'px'
}

export function isAndroid() {
  return /android/.test(navigator.userAgent.toLowerCase())
}
/**
 * 获取连接参数
 * @param {*} variable 参数名
 */
export function getQueryVariable(variable) {
  var rs = new RegExp('(^|)' + variable + '=([^&]*)(&|$)', 'gi').exec(window.document.location.href)
  var tmp
  if ((tmp = rs)) {
    tmp[2] = tmp[2].split('?')[0]
    tmp[2] = tmp[2].split('#')[0]
    return tmp[2]
  }
  return ''
}

export function compareVersion(version) {
  // 获取拜访助手模块版本号
  const matchs = /[^a-zA-Z]AI_V(=)*([\d]+)?/.exec(navigator.userAgent)
  console.log('user-agent-version', matchs)
  if (!matchs) {
    // 非 口袋E APP 中，也可能是旧版本没有AI_V字段
    return -1
  } else {
    const temp = Number(matchs[2])
    // 没有给指定版本号，默认为最新版本
    if (!version) {
      return 1
    }
    // 当前版本小于指定版本
    if (temp < parseInt(version)) {
      return -1
    }
    // 当前版本等于指定版本
    if (temp === parseInt(version)) {
      return 0
    }

    // 当前版本大于指定版本
    return 1
  }
}

export function checkInApp() {
  const matchs1 = /[^a-zA-Z]AI_V(=)*([\d]+)?/.exec(navigator.userAgent)
  const matchs2 = /[^a-zA-Z]ESALESAPP_V([.\d]+)[^.\d]?/.exec(navigator.userAgent)
  if (!matchs1 && !matchs2) {
    return false
  }
  return true
}
export function checkInAppTrain() {
  const matchs2 = /[^a-zA-Z]AITrainSDK/.exec(navigator.userAgent)
  if (matchs2) {
    return true
  }
  return false
}

export function generateParentCode() {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4'
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
  s[8] = s[13] = s[18] = s[23] = '-'
  const uuid = s.join('')
  return uuid
}

export async function shareInfo() {
  const params = await shareIdCallBack()
  let shareId = ''
  let agentNo = ''
  try {
    const info = JSON.parse(params)
    shareId = info ? info.shareId : ''
    agentNo = info ? info.agentNo : ''
  } catch (error) {
    shareId = params ? params.shareId : ''
    agentNo = params ? params.agentNo : ''
  }
  return { shareId, agentNo }
}

export function transformUrlToData(url) {
  return new Promise((resolve, reject) => {
    if (!url || url.length <= 0) resolve('')
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.crossOrigin = 'Anonymous'
    img.src = url + '?timeStamp=' + new Date().getTime()
    img.onload = function () {
      canvas.height = img.height
      canvas.width = img.width
      ctx.drawImage(img, 0, 0)
      const dataUrl = canvas.toDataURL('image/png')
      const base64String = dataUrl.substr(dataUrl.indexOf(',') + 1)
      const padding = '='.repeat((4 - (base64String.length % 4)) % 4)
      const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/')
      const rawData = window.atob(base64)
      const outputArray = new Uint8Array(rawData.length)
      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i)
      }
      const blobUrl = window.URL.createObjectURL(new Blob([outputArray], { type: 'image/png' }))
      resolve(blobUrl)
    }
    img.onerror = function (e) {
      resolve('')
    }
  })
}

export async function getAccountInfos() {
  let params = ''
  let name = ''
  let avatar = ''
  let agentNo = ''
  if (checkInApp()){
    params = await getAccountInfo()
    try {
      const agentInfo = JSON.parse(params)
      name = agentInfo ? agentInfo.agentName : ''
      avatar = agentInfo ? agentInfo.avatarUrl : ''
      agentNo = agentInfo ? agentInfo.agentNo : ''
    } catch (error) {
      name = params ? params.agentName : ''
      avatar = params ? params.avatarUrl : ''
      agentNo = params ? params.agentNo : ''
    }
  }else{ //非口袋app浏览器环境模拟
    name = '姓名'
    avatar = ''
    agentNo = "1120103025"
  }
  return { name, avatar, agentNo }
}

export function loadScript(url) {
  return new Promise(resolve => {
    var s = document.createElement('script')
    s.setAttribute('src', url)
    s.onload = function () {
      resolve(true)
    }
    s.onerror = function () {
      resolve(false)
    }
    document.body.appendChild(s)
  })
}

// 轮播图动画
export function animate(ele, target, current, move) {
  clearInterval(ele.timerId)
  ele.timerId = setInterval(function () {
    let step = move > 0 ? 10 : -10
    if (Math.abs(current * target - -ele.offsetLeft) > Math.abs(step)) {
      ele.style.marginLeft = -Math.abs(ele.offsetLeft + -step) + 'px'
    } else {
      ele.style.marginLeft = -current * target + 'px'
      clearInterval(ele.timerId)
    }
  }, 10)
}

/**
 * 获取iPhone全面屏底部的空白条区域高度
 */
var SafeareaBottomPx = -1
export function getSafeareaBottomPx() {
  if (SafeareaBottomPx === -1) {
    const val = getComputedStyle(document.documentElement).getPropertyValue('--safe-area-inset-bottom')
    const match = /^(\d+)px$/.exec(val)
    if (match) {
      SafeareaBottomPx = Number(match[1])
    } else {
      // 非iPhone全面屏
      SafeareaBottomPx = 0
    }
  }
  return SafeareaBottomPx
}

/**
 * 获取iPhone全面屏顶部刘海区域高度
 */
var SafeareaTopPx = -1
export function getStatusbarHeightPx() {
  if (SafeareaTopPx === -1) {
    const val = getComputedStyle(document.documentElement).getPropertyValue('--safe-area-inset-top')
    const match = /^(\d+)px$/.exec(val)
    if (match) {
      SafeareaTopPx = Number(match[1])
    } else {
      // 非iPhone全面屏
      SafeareaTopPx = 0
    }
  }
  return SafeareaTopPx
}

/**
 * 是否显示标题栏
 */
export function getIfShowNavbar() {
  return true
  // return getStatusbarHeight() > 0
}

/**
 * 获取状态栏+标题栏的总高度
 */
export function getNavbarHeightPx() {
  if (!getIfShowNavbar()) return 0
  return PX(getStatusbarHeight() + 88)
}

/**
 * 获取状态栏的逻辑单位高度
 */
export function getStatusbarHeight() {
  return RPX(getStatusbarHeightPx())
}

/**
 * 手机号验证
 */
export function isPhone(value) {
  const reg = /^[1][3,4,5,7,8][0-9]{9}$/;
  return reg.test(value)
}

export function newGetUrlParams(name) {
  let url = window.location.href
  url = url.split("?")[1]
  const urlParams = new URLSearchParams(url)
  const params = Object.fromEntries(urlParams.entries())
  return params[name]
}
